package com.zrt.bookstore3.Controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zrt.bookstore3.Controller.utils.R;
import com.zrt.bookstore3.Domain.Book;
import com.zrt.bookstore3.Domain.User;
import com.zrt.bookstore3.Service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book){
        System.out.println("参数==>"+book);

        IPage<Book> page = bookService.getPage(currentPage, pageSize,book);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > page.getPages()){
            page = bookService.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true, page);
    }

    @PostMapping("/listBooksByType")
    public R listBooksByType(@RequestBody Book book){
        int categoryId = book.getCategoryId();
        return new R(true,bookService.selectAllBooksByCondition(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id){
        return new R(bookService.delete(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id, HttpServletRequest request){
        System.out.println("----------------------------------");
        System.out.println(id);
        request.getSession().setAttribute("bookId",id);
        System.out.println("----------------------------------");
        System.out.println(bookService.selectById(id));
        return new R(true, bookService.selectById(id));
    }


    @PutMapping
    public R update(@RequestBody Book book) throws IOException {
        //if (book.getName().equals("123") ) throw new IOException();
        boolean flag = bookService.modify(book);
        return new R(flag, flag ? "修改成功^_^" : "修改失败-_-!");
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
//        R r = new R();
//        boolean flag = bookService.save(book);
//        r.setFlag(flag);
        System.out.println("------------------------");
        System.out.println(book.getId());
        System.out.println("------------------------");
        //if (book.getName().equals("123") ) throw new IOException();
        boolean flag = bookService.save(book);
        return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
    }

    @GetMapping
    public R getAll(){
        return new R(true, bookService.selectAll());
    }

}
